package com.wisdom.voip;


import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hisun.phone.core.voice.Device;
import com.hisun.phone.core.voice.DeviceListener.Reason;
import com.hisun.phone.core.voice.Log4Util;
import com.hisun.phone.core.voice.VoiceUtil;
import org.sipdroid.sipua.R;
import org.sipdroid.sipua.ui.Receiver;

import com.wisdom.VoiceApplication;
import com.wisdom.tools.CCPConfig;
import com.wisdom.tools.CCPUtil;

public class CallOutActivity extends Activity implements OnClickListener{
	// 计时器
	private Timer mTimer;
	// 计时
		private long mTime = 0;
	// 通话 ID
	private String mCurrentCallId;
	// 话筒调节控制区
		private LinearLayout mCallAudio;
		// 静音按钮
		private ImageView mCallMute;
		// 免提按钮
		private ImageView mCallHandFree;
		// 键盘
		private ImageView mDiaerpadBtn;
		//键盘区
		private LinearLayout mDiaerpad;
		
		// 挂机按钮
		private ImageView mVHangUp;
		// 动态状态显示区
		private TextView mCallStateTips;
		// 状态栏
		private NotificationManager mNotificationManager;
	// 通话类型，直拨，落地, 回拨
	private String mType = "";
	// voip 账号
	private String mVoipAccount;
	// 号码显示区
	private TextView mVtalkNumber;
	 private VoiceHelper mHelper;
	 private EditText mDmfInput;
		// activity 标签
		private static final String TAG = "CallOutActivity";
		// 通话状态
		private boolean isConnect = false;
		// 是否静音
		private boolean isMute = false;
		// 是否免提
		private boolean isHandsfree = false;
		// 是否键盘显示
		private boolean isDialerShow = false;
		// 手动挂断
		private boolean isSelfReject = false;
	// 号码
		private String mPhoneNumber;
      @Override
      protected void onCreate(Bundle savedInstanceState){
    	  super.onCreate(savedInstanceState);
    	  setContentView(R.layout.layout_call_interface);
    	  initResourceRefs();
    	  initialize();
    	  initCall();
      }
    /**
     * 回调handler，根据Voip通话状态，更新界面显示
     */
    private android.os.Handler mHandler=new android.os.Handler(){
    	@Override
    	public void handleMessage(Message msg){
    		super.handleMessage(msg);
    		String callid=null;
    		Reason reason;
    		Bundle b=null;
    		//获取通话ID
    		if(msg.obj instanceof String){
    			callid=(String)msg.obj;
    			
    		}else if(msg.obj instanceof Bundle){
    			b=(Bundle)msg.obj;
    			callid=b.getString(Device.CALLID);
    			
    		}
    		switch(msg.what){
    		case 1:
    			//计时
    			if(mTimer!=null){
    				mTime++;
    			
    			if(isConnect){
    				mCallStateTips.setText(CCPUtil.getCallDurationShow(mTime));
    			}
    			}
    			break;
    		case VoiceHelper.WHAT_ON_CALL_ALERTING:
    			// 连接到对端用户，播放铃声
    			Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] voip alerting!!");
    			if(callid!=null&&mCurrentCallId.equals(callid)){
    				mCallStateTips.setText(R.string.voip_calling_wait);
    			}
    			break;
    		case VoiceHelper.WHAT_ON_CALL_PROCEEDING:
    			//连接到服务器
    			Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] voip on call proceeding!!");
    			if(callid!=null&&mCurrentCallId.equals(callid)){
    				mCallStateTips.setText(getString(R.string.voip_call_connect));
    			}
    			break;
    		case VoiceHelper.WHAT_ON_CALL_ANSWERED:
    			//对端应答
    			Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] voip on call answered!!");
    			if(callid!=null&&mCurrentCallId.equals(callid)){
    				isConnect=true;
    				mCallMute.setEnabled(true);
    				mTime=0;
    				mTimer=new Timer();
    				mTimer.schedule(task, 0,1000);
    				
    			}
    			break;
    		case VoiceHelper.WHAT_ON_CALL_RELEASED:
    			//远端挂断，本地挂断在onClick中处理
    			Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] voip on call released!!");
    			if(callid!=null&&mCurrentCallId.equals(callid)&&!isSelfReject){
    				finishCalling();
    			}
    			break;
    		
    		case VoiceHelper.WHAT_ON_CALL_MAKECALL_FAILED:
    			//发起通话失败
    			Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] voip on call makecall failed!!");
    			if (b != null && b.get(Device.REASON) != null) {
					reason = (Reason) b.get(Device.REASON);
					Log.d(TAG, "reason:"+reason);
					if (callid != null && mCurrentCallId.equals(callid) && !isSelfReject) {
						finishCalling(reason);
					}
				}
				break;
    		}	
    		
    	}
    };
    /**
	 * 根据状态,修改按钮属性及关闭操作
	 * 
	 * @param reason
	 */
	private void finishCalling(Reason reason) {
		try {
			if (mTimer != null) {
				mTimer.cancel();
				mTimer = null;
			}
			mHandler.postDelayed(finish, 5000);
			mCallHandFree.setClickable(false);
			mCallMute.setClickable(false);
			mVHangUp.setClickable(false);
			mDiaerpadBtn.setClickable(false);
			mDiaerpadBtn.setImageResource(R.drawable.call_interface_diaerpad);
			mCallHandFree.setImageResource(R.drawable.call_interface_hands_free);
			mCallMute.setImageResource(R.drawable.call_interface_mute);
			mVHangUp.setBackgroundResource(R.drawable.call_interface_non_red_button);
			// 处理通话结束状态
			if (reason == Reason.DECLINED) {
				mCallStateTips.setText(getString(R.string.voip_calling_refuse));
			} else if (reason == Reason.CALLMISSED) {
				mCallStateTips.setText(getString(R.string.voip_calling_timeout));
			} else if (reason == Reason.PAYMENT) {
				mCallStateTips.setText(getString(R.string.voip_call_fail_no_cash));
			} else if (reason == Reason.UNKNOWN) {
				mCallStateTips.setText(getString(R.string.voip_calling_finish));
			} else if (reason == Reason.NOTRESPONSE) {
				mCallStateTips.setText(getString(R.string.voip_call_fail));
			} else {
				mCallStateTips.setText(getString(R.string.voip_calling_network_instability));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    /**
     * 用于挂断时修改按钮属性及关闭操作
     */
    private void finishCalling(){
    	
    	try{
    		if(mTimer!=null){
    			mTimer.cancel();
    			mTimer=null;
    		}
    		if(isConnect){
    			//接通后关闭
    			mCallStateTips.setText(R.string.voip_calling_finish);
    			mHandler.postDelayed(finish,3000);
    		}else{
    			//未接通，直接关闭
    			finish();
    		}
    		mCallHandFree.setClickable(false);
    		mCallMute.setClickable(false);
    		mVHangUp.setClickable(false);
    		mDiaerpadBtn.setClickable(false);
    		mDiaerpadBtn.setImageResource(R.drawable.call_interface_diaerpad);
    		mCallHandFree.setImageResource(R.drawable.call_interface_hands_free);
			mCallMute.setImageResource(R.drawable.call_interface_mute);
			mVHangUp.setBackgroundResource(R.drawable.call_interface_non_red_button);
    	} catch (Exception e) {
			e.printStackTrace();
		}
    }
    /**
	 * 延时关闭界面
	 */
	final Runnable finish = new Runnable() {
		public void run() {
			finish();
		}
	};
    /**
	 * 计时器
	 */
	TimerTask task = new TimerTask() {
		public void run() {
			Message message = new Message();
			message.what = 1;
			mHandler.sendMessage(message);
		}
	};
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		
		// keypad
		case R.id.zero:{
			keyPressed(KeyEvent.KEYCODE_0);
			return ;
		}
		case R.id.one:{
			keyPressed(KeyEvent.KEYCODE_1);
			return ;
		}
		case R.id.two:{
			keyPressed(KeyEvent.KEYCODE_2);
			return ;
		}
		case R.id.three:{
			keyPressed(KeyEvent.KEYCODE_3);
			return ;
		}
		case R.id.four:{
			keyPressed(KeyEvent.KEYCODE_4);
			return ;
		}
		case R.id.five:{
			keyPressed(KeyEvent.KEYCODE_5);
			return ;
		}
		case R.id.six:{
			keyPressed(KeyEvent.KEYCODE_6);
			return ;
		}
		case R.id.seven:{
			keyPressed(KeyEvent.KEYCODE_7);
			return ;
		}
		case R.id.eight:{
			keyPressed(KeyEvent.KEYCODE_8);
			return ;
		}
		case R.id.nine:{
			keyPressed(KeyEvent.KEYCODE_9);
			return ;
		}
		case R.id.star:{
			keyPressed(KeyEvent.KEYCODE_STAR);
			return ;
		}
		case R.id.pound:{
			keyPressed(KeyEvent.KEYCODE_POUND);
			return ;
		}
		
		// keybad end ...
		
		case R.id.layout_call_reject:
			// 挂断电话
			Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] Voip talk hand up, CurrentCallId " + mCurrentCallId);
			isSelfReject = true;
			try {
				if (mCurrentCallId != null) {
					getDevice().releaseCall(mCurrentCallId, 0);
				} 
			} catch (Exception e) {
				e.printStackTrace();
			}
			finish();
			break;
		case R.id.layout_callin_mute:
			// 设置静音
			setMuteUI();
			break;
		case R.id.layout_callin_handfree:
			// 设置免提
			sethandfreeUI();
			break;
			
		case R.id.layout_callin_diaerpad:
			
			// 设置键盘
			setDialerpadUI();
			break;
		default:
			break;
		}
	}
	/**
	 * 设置静音
	 */
	private void setMuteUI() {
		try {
			if (isMute) {
				mCallMute.setImageResource(R.drawable.call_interface_mute);
			} else {
				mCallMute.setImageResource(R.drawable.call_interface_mute_on);
			}
			getDevice().setMute(isMute);
			isMute = getDevice().getMuteStatus();
			Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] 设置通话静音");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	void setDialerpadUI() {
		if(isDialerShow) {
			mDiaerpadBtn.setImageResource(R.drawable.call_interface_diaerpad);
			mDiaerpad.setVisibility(View.GONE);
			isDialerShow = false;
		} else {
			mDiaerpadBtn.setImageResource(R.drawable.call_interface_diaerpad_on);
			mDiaerpad.setVisibility(View.VISIBLE);
			isDialerShow = true;
		}
		
	}
	/**
	 * 设置免提
	 */
	private void sethandfreeUI() {
		try {
			if (isHandsfree) {
				mCallHandFree.setImageResource(R.drawable.call_interface_hands_free);
			} else {
				mCallHandFree.setImageResource(R.drawable.call_interface_hands_free_on);
			}
			getDevice().enableLoudsSpeaker(isHandsfree);
			isHandsfree = getDevice().getLoudsSpeakerStatus();
			Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] 设置通话免提");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取Device
	 * @return
	 */
	private Device getDevice() {
		return mHelper.getDevice();
	}
	private static AlertDialog m_AlertDlg;
	private void initCall(){
		String target = "11"+mPhoneNumber;
		if (m_AlertDlg != null) 
		{
			m_AlertDlg.cancel();
		}
		if (target.length() == 0)
			m_AlertDlg = new AlertDialog.Builder(this)
				.setMessage(R.string.empty)
				.setTitle(R.string.app_name)
				.setIcon(R.drawable.icon22)
				.setCancelable(true)
				.show();
		else if (!Receiver.engine(this).call(target,true))
			m_AlertDlg = new AlertDialog.Builder(this)
				.setMessage(R.string.notfast)
				.setTitle(R.string.app_name)
				.setIcon(R.drawable.icon22)
				.setCancelable(true)
				.show();
		return;
		
		/*try {
			mHelper = VoiceApplication.getInstance().getVoiceHelper();
			mHelper.setHandler(mHandler);
			if (mType.equals(VoiceApplication.VALUE_DIAL_MODE_FREE)) {
				// voip免费通话
				if (mVoipAccount != null && !TextUtils.isEmpty(mVoipAccount)) {
					mCurrentCallId = getDevice().makeCall(Device.CallType.VOICEP2P, mVoipAccount);
					Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] VoIP calll, mVoipAccount " + mVoipAccount + " currentCallId " +  mCurrentCallId);
				}
			} else if (mType.equals(VoiceApplication.VALUE_DIAL_MODE_DIRECT)) {
				// 直拨
				mCurrentCallId = getDevice().makeCall(Device.CallType.VOICEP2L, VoiceUtil.getStandardMDN(mPhoneNumber));
				Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] Direct dial, mPhoneNumber " + mPhoneNumber + " currentCallId " +  mCurrentCallId);
			}  else if (mType.equals(VoiceApplication.VALUE_DIAL_MODE_BACK)) {
				// 回拨
				mHelper.getDevice().makeCallBack(CCPConfig.Src_phone, mPhoneNumber);
				mCallAudio.setVisibility(View.GONE);
				Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] call back, mPhoneNumber " + mPhoneNumber);
				return;
			} else {
				finish();
				return;
			}

			if (mCurrentCallId == null || mCurrentCallId.length() < 1) {
				VoiceApplication.getInstance().showToast(R.string.no_support_voip);
				Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] Sorry, "+ getString(R.string.no_support_voip)+" , Call failed. ");
				finish();
				return;
			}
			isMute = getDevice().getMuteStatus();
			isHandsfree = getDevice().getLoudsSpeakerStatus();
		} catch (Exception e) {
			finish();
			Log4Util.d(VoiceHelper.WISDOMCALL_TAG ,"[CallOutActivity] Sorry, call failure leads to an unknown exception, please try again. ");
			e.printStackTrace();
		}
		*/
	}
	private void initialize(){
		Intent intent=getIntent();
		if(intent!=null){
			Bundle bundle=intent.getExtras();
			if(bundle==null){
				finish();
				return;
			}
			mType=bundle.getString(VoiceApplication.VALUE_DIAL_MODE);
			
			if(mType.equals(VoiceApplication.VALUE_DIAL_MODE_FREE)){
				//voip免费通话时显示voip账号
				mVoipAccount=bundle.getString(VoiceApplication.VALUE_DIAL_VOIP_INPUT);
				if(mVoipAccount==null){
					finish();
					return;
				}
				mVtalkNumber.setText(mVoipAccount);
				
			}else{
				//直播及回拨显示号码
				mPhoneNumber=bundle.getString(VoiceApplication.VALUE_DIAL_VOIP_INPUT);
				mVtalkNumber.setText(mPhoneNumber);
			}
		}
	}
	private void initResourceRefs(){
		mCallAudio=(LinearLayout)findViewById(R.id.layout_call_audio);
		mCallMute = (ImageView) findViewById(R.id.layout_callin_mute);
		mCallHandFree = (ImageView) findViewById(R.id.layout_callin_handfree);
		mVHangUp = (ImageButton) findViewById(R.id.layout_call_reject);
		mCallStateTips = (TextView) findViewById(R.id.layout_callin_duration);
		mVtalkNumber = (TextView) findViewById(R.id.layout_callin_number);
		// 键盘按钮
		mDiaerpadBtn = (ImageView) findViewById(R.id.layout_callin_diaerpad);
		mDiaerpad = (LinearLayout) findViewById(R.id.layout_diaerpad);
		
		mDiaerpadBtn.setOnClickListener(this);
		mCallMute.setOnClickListener(this);
		mCallHandFree.setOnClickListener(this);
		mVHangUp.setOnClickListener(this);
		mCallMute.setEnabled(false);
		mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(
				Context.NOTIFICATION_SERVICE);
		showNotification(getString(R.string.notification_calling_title),
				getString(R.string.notification_calling_content));
		
		
		setupKeypad();
		mDmfInput = (EditText) findViewById(R.id.dial_input_numer_TXT);
		
	}
	void keyPressed(int keyCode) {
        KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
        mDmfInput.getText().clear();
		mDmfInput.onKeyDown(keyCode, event);
		getDevice().sendDTMF(mCurrentCallId, mDmfInput.getText().toString().toCharArray()[0]);
    }
	private void setupKeypad() {
		/**Setup the listeners for the buttons*/
		findViewById(R.id.zero).setOnClickListener(this);
		findViewById(R.id.one).setOnClickListener(this);
		findViewById(R.id.two).setOnClickListener(this);
		findViewById(R.id.three).setOnClickListener(this);
		findViewById(R.id.four).setOnClickListener(this);
		findViewById(R.id.five).setOnClickListener(this);
		findViewById(R.id.six).setOnClickListener(this);
		findViewById(R.id.seven).setOnClickListener(this);
		findViewById(R.id.eight).setOnClickListener(this);
		findViewById(R.id.nine).setOnClickListener(this);
		findViewById(R.id.star).setOnClickListener(this);
		findViewById(R.id.pound).setOnClickListener(this);
	}
	/**
	 * 显示状态栏
	 * @param topic
	 * @param text
	 */
	@SuppressWarnings("deprecation")
	private void showNotification(String topic, String text) {
		try {
			@SuppressWarnings("deprecation")
			Notification notification = new Notification(R.drawable.icon_call_small, text,
					System.currentTimeMillis());
			notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_SHOW_LIGHTS;
			Intent intent = new Intent("ACTION_VOIP_OUTCALL");
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			notification.setLatestEventInfo(this, topic, text, contentIntent);
			mNotificationManager.notify(R.drawable.icon_call_small, notification);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	protected void onDestroy() {
		if (isMute && getDevice() != null) {
			getDevice().setMute(isMute);
		}
		if (isHandsfree && getDevice() != null) {
			getDevice().enableLoudsSpeaker(isHandsfree);
		}
		if (mVHangUp != null) {
			mVHangUp = null;
		}
		if (mCallAudio != null) {
			mCallAudio = null;
		}
		if (mCallStateTips != null) {
			mCallStateTips = null;
		}
		if (mVtalkNumber != null) {
			mVtalkNumber = null;
		}
		if (mCallMute != null) {
			mCallMute = null;
		}
		if (mCallHandFree != null) {
			mCallHandFree = null;
		}
		if (mDiaerpadBtn != null) {
			mDiaerpadBtn = null;
		}
		if (mNotificationManager != null) {
			mNotificationManager.cancel(R.drawable.icon_call_small);
			mNotificationManager = null;
		}
		mPhoneNumber = null;
		mVoipAccount = null;
		mCurrentCallId = null;
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if(mHandler!=null){
			mHandler = null;
		}
		VoiceApplication.getInstance().setAudioMode(AudioManager.MODE_NORMAL);
		super.onDestroy();
	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 屏蔽返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
